package com.yihukurama.sysbase.controller;


import com.yihukurama.base.app.cache.RedisUtils;
import com.yihukurama.base.app.constant.Constant;
import com.yihukurama.base.framework.web.dto.Request;
import com.yihukurama.base.framework.web.dto.Result;
import com.yihukurama.sysbase.common.utils.StringUtils;
import com.yihukurama.sysbase.controller.dto.SysCache;
import com.yihukurama.sysbase.controller.vo.Server;
import com.yihukurama.sysbase.framework.domain.User;
import com.yihukurama.sysbase.sysservice.ISystem;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 说明： 系统模块接口
 *
 * @Author yihukurma
 * @date Created in 下午 1:21 2023/7/27 0027
 * modified by yihukurama in 下午 1:21 2023/7/27 0027
 */
@Api(value = "System API", tags = "系统API")
@RestController
@RequestMapping("/system")
@CrossOrigin(origins = "*", maxAge = 3600)
public class SystemController {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    ISystem iSystem;
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public Result logout(@RequestBody Request<User> request) throws Exception {

        return iSystem.logout(request);
    }

    @RequestMapping(value = "/get_rolutes", method = RequestMethod.POST)
    public Result getRolutes(@RequestBody Request<User> request) throws Exception {

        return iSystem.getRoutes(request);
    }


    /**
     * 查询在线用户
     * @param request
     * @return
     */
    @RequestMapping(value = "/onlineuser", method = RequestMethod.POST)
    public Result onlineuser(@RequestBody Request<User> request)
    {

        List<User> userList = new ArrayList<>();
        Set<String> set = redisUtils.getKeys("online*");
        for (String key:set
             ) {
            User u = (User)redisUtils.get(key);
            userList.add(u);
        }
        return Result.successed(userList);
    }

    /**
     * 查询主机状况
     * @param request
     * @return
     */
    @RequestMapping(value = "/server", method = RequestMethod.POST)
    public Result server(@RequestBody Request<Object> request) throws Exception {
        Server server = new Server();
        server.copyTo();
        return Result.successed(server);
    }

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @RequestMapping(value = "/cache", method = RequestMethod.POST)
    public Result cacheInfo(@RequestBody Request<Object> request) throws Exception
    {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);
        return Result.successed(result,"访问成功");
    }


    private final static List<SysCache> caches = new ArrayList<SysCache>();
    {
        caches.add(new SysCache(Constant.LOGIN_TOKEN_KEY, "用户信息"));
        caches.add(new SysCache(Constant.SYS_CONFIG_KEY, "配置信息"));
        caches.add(new SysCache(Constant.SYS_DICT_KEY, "数据字典"));
        caches.add(new SysCache(Constant.CAPTCHA_CODE_KEY, "验证码"));
        caches.add(new SysCache(Constant.REPEAT_SUBMIT_KEY, "防重提交"));
        caches.add(new SysCache(Constant.RATE_LIMIT_KEY, "限流处理"));
        caches.add(new SysCache(Constant.PWD_ERR_CNT_KEY, "密码错误次数"));
    }
    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @RequestMapping(value = "/cache/getNames", method = RequestMethod.POST)
    public Result cache(@RequestBody Request<Object> request)
    {
        return Result.successed(caches);
    }

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @RequestMapping(value = "cache/getKeys",method = RequestMethod.POST)
    public Result getCacheKeys(@RequestBody Request<String> request)
    {
        Set<String> cacheKeys = redisTemplate.keys(request.getData() + "*");
        return Result.successed(cacheKeys);
    }


    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @RequestMapping(value = "cache/getValue",method = RequestMethod.POST)
    public Result getCacheValue(@RequestBody Request<SysCache> request)
    {
        SysCache sysCache = request.getData();
        String cacheValue = redisTemplate.opsForValue().get(sysCache.getCacheKey());
        sysCache.setCacheValue(cacheValue);
        return Result.successed(sysCache);
    }

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @RequestMapping(value = "cache/clearCacheName",method = RequestMethod.POST)
    public Result clearCacheName(@RequestBody Request<String> request)
    {
        Collection<String> cacheKeys = redisTemplate.keys(request.getData() + "*");
        redisTemplate.delete(cacheKeys);
        return Result.successed("操作成功");
    }

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @RequestMapping(value = "cache/clearCacheKey",method = RequestMethod.POST)
    public Result clearCacheKey(@RequestBody Request<String> request)
    {
        redisTemplate.delete(request.getData());
        return Result.successed("操作成功");
    }

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")
    @RequestMapping(value = "cache/clearCacheAll",method = RequestMethod.POST)
    public Result clearCacheAll(@RequestBody Request<Object> request)
    {
        Collection<String> cacheKeys = redisTemplate.keys("*");
        redisTemplate.delete(cacheKeys);
        return Result.successed("操作成功");
    }

}

